package com.example.tang.zhayan.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.tang.zhayan.R;
import com.example.tang.zhayan.adapter.DesignerPagerAdapter;
import com.example.tang.zhayan.bean.BaseDesignerBody;
import com.example.tang.zhayan.bean.BaseDesignerHead;
import com.example.tang.zhayan.bean.DesignerBodyItem;
import com.example.tang.zhayan.bean.DesignerHeadData;
import com.example.tang.zhayan.bean.DesignerHeadUser;
import com.example.tang.zhayan.constant.PathConstant;
import com.example.tang.zhayan.utils.ImgOptionsUtils;
import com.example.tang.zhayan.utils.ResultParamsUtils;
import com.squareup.picasso.Picasso;

import org.simple.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.inovex.android.widgets.ViewPager3D;

/**
 * Created by yang on 2015/12/16.
 */
@ContentView(R.layout.activity_designer)
public class DesignerActivity extends AppCompatActivity implements View.OnClickListener {

    @ViewInject(R.id.back_iv)
    private ImageView iv_back;

    @ViewInject(R.id.iv_locate)
    private ImageView iv_locate;

    @ViewInject(R.id.iv_icon)
    private ImageView iv_icon;

    @ViewInject(R.id.tv_name)
    private TextView tv_name;

    @ViewInject(R.id.tv_weixin)
    private TextView tv_weixin;

    @ViewInject(R.id.tv_attention)
    private TextView tv_attention;

    @ViewInject(R.id.vp)
    private ViewPager3D viewPager;

    @ViewInject(R.id.rl_vp)
    private RelativeLayout rl_vp;

    //点击首页传过来的Memberid
    private String id = "";

    private List<DesignerBodyItem> list = new ArrayList<>();

    private DesignerPagerAdapter pagerAdapter;
    private List<View> viewList = new ArrayList<>();

    private EventBus bus = EventBus.getDefault();
    private DesignerHeadUser user;
    private SharedPreferences preferences;
    private String name = "";
    private String icon = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        preferences = getSharedPreferences("userMsg", Context.MODE_PRIVATE);
        name = preferences.getString("userName", "no");
        icon = preferences.getString("icon", "no");
        Intent intent = getIntent();
        if (intent != null) {
            id = intent.getStringExtra("designerMemberId");
        }
        initView();
        initData();

    }

    /**
     * 初始化控件和控件监听
     */
    private void initView() {
        tv_weixin.setOnClickListener(this);
        tv_attention.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_locate.setOnClickListener(this);
        pagerAdapter = new DesignerPagerAdapter(viewList);
        //viewpager  每一项的点击事件
        pagerAdapter.setClick(new DesignerPagerAdapter.SetPageClick() {
            @Override
            public void setOnPageClick(int position) {
                Intent intent = new Intent(DesignerActivity.this, BuyDetailsActivity.class);
                intent.putExtra("id", list.get(position).getId());
                intent.putExtra("memberId", id);
                startActivity(intent);
            }
        });
        viewPager.setOffscreenPageLimit(3);
        viewPager.setPageMargin(10);
        viewPager.setAdapter(pagerAdapter);
        rl_vp.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // dispatch the events to the ViewPager, to solve the problem that we can swipe only the middle view.
                return viewPager.dispatchTouchEvent(event);
            }
        });

        MyOnPageChangeListener myOnPageChangeListener = new MyOnPageChangeListener();
        viewPager.setOnPageChangeListener(myOnPageChangeListener);
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // to refresh frameLayout
            if (rl_vp != null) {
                rl_vp.invalidate();
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        createHeadData();
        createBodyData();
    }

    public Map<String, String> getMap() {
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        return map;
    }

    public ImageOptions getOptions() {
        ImageOptions options = new ImageOptions.Builder()
                .setLoadingDrawableId(R.mipmap.default_loader_image1)
                .setFailureDrawableId(R.mipmap.default_loader_image1)
                .setImageScaleType(ImageView.ScaleType.FIT_XY)
                .build();
        return options;
    }

    /**
     * 创建设计师界面主题的数据
     */
    private void createBodyData() {
        x.http().post(ResultParamsUtils.getIDParams(PathConstant.DESIGNER_BODY_IMG, getMap()), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                BaseDesignerBody body = JSONObject.parseObject(result, BaseDesignerBody.class);
                list = body.getData().getList();
                for (int i = 0; i < list.size(); i++) {
                    View v = LayoutInflater.from(DesignerActivity.this).inflate(R.layout.item_designer_pager_layout, null);
                    ImageView imageView = (ImageView) v.findViewById(R.id.iv_page);
                    TextView tv_old_price = (TextView) v.findViewById(R.id.tv_old_price);
                    TextView tv_new_price = (TextView) v.findViewById(R.id.tv_new_price);
                    tv_new_price.setText("￥" + list.get(i).getNew_prc());
                    tv_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    tv_old_price.setText("￥" + list.get(i).getOld_prc());
                    x.image().bind(imageView, list.get(i).getCover(), getOptions());
                    viewList.add(v);
                }
                pagerAdapter.notifyDataSetChanged();
                viewPager.setCurrentItem(1);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 创建设计师界面头部的数据
     */
    private void createHeadData() {

        x.http().post(ResultParamsUtils.getIDParams(PathConstant.DESIGNER_HEAD, getMap()), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                BaseDesignerHead head = JSONObject.parseObject(result, BaseDesignerHead.class);
                DesignerHeadData data = head.getData();
                user = data.getUser();
                tv_name.setText(user.getName());

                Picasso.with(DesignerActivity.this).load(user.getIcon()).placeholder(R.mipmap.
                        default_loader_image1).into(iv_icon);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    /**
     * 头部发私信 和 关注的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_weixin:
            case R.id.tv_attention:
                if (!name.equals("no")) {
                    Intent intent = new Intent(this, UserActivity.class);
                    intent.putExtra("icon",icon);
                    intent.putExtra("userName",name);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(this, UserLoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.back_iv:
                this.finish();
                break;
            case R.id.iv_locate:
                if (user.getName() != null) {
                    Intent map = new Intent(this, MapActivity.class);
                    map.putExtra("storeName", user.getName());
                    startActivity(map);
                    break;
                }
        }
    }
}
